import * as step from '@flow-step/step-toolkit'
import * as fs from 'fs'
import {IGitSourceParams} from './git-source-params'
import * as util from './util'
import {ensureDirectoryExists} from './util'
import axios from 'axios'
import * as path from 'node:path'

export function createPackagesSource() {
    return new PackagesSource();
}

export class PackagesSource {

    async handlePackagesSource(sourceParams: IGitSourceParams) {
        await this.downloadPackages(sourceParams)
        await this.writePackagesInfo(sourceParams)
    }
    
    async downloadPackages(sourceParams: IGitSourceParams) {
        step.info(`Use Packages as source`)
        if (fs.existsSync(sourceParams.projectDir)) {
            util.clearDir(sourceParams.projectDir)
        } else {
            fs.mkdirSync(sourceParams.projectDir)
        }
        // 处理自定义下载路径
        let downloadPathWithoutDir = sourceParams.artifactName;
        let fileDownloadPath = path.join(sourceParams.projectDir, `${downloadPathWithoutDir}_${sourceParams.versionName}.tgz`);
        if (sourceParams.packagesFilePath) {
            downloadPathWithoutDir = sourceParams.packagesFilePath.startsWith('/') ? sourceParams.packagesFilePath.substring(1) : sourceParams.packagesFilePath;
            fileDownloadPath =  path.join(sourceParams.projectDir, downloadPathWithoutDir);
            if(downloadPathWithoutDir.includes('/')){
                const artifactDir = path.dirname(downloadPathWithoutDir);
                step.info(`artifactDir is ${artifactDir}`)
                if (artifactDir !== '.' && artifactDir !== '') {
                    ensureDirectoryExists(fileDownloadPath);

                }
            }

        }else{
            //针对下载手动上传到packages的制品：如果sourceParams.artifactName中包含路径分隔符，比如demo/Artifact_dafjids.tgz，需要先创建出demo目录
            if (sourceParams.artifactName.includes('/')) {
                ensureDirectoryExists(fileDownloadPath);
            }
        }
        step.info(`Use downloadPath value is ${fileDownloadPath}`)




        step.info(`Download packages from ${sourceParams.repoUrl}/api/protocol/${sourceParams.orgId}/${sourceParams.repoType}/${sourceParams.repoId}/files/${sourceParams.artifactName}?signUrl=true&userId=${sourceParams.user}&version=${sourceParams.versionName}`)
        //step.info(`package credential: ${sourceParams.token}`)
        let packagesApi = `${sourceParams.repoUrl}/api/protocol/${sourceParams.orgId}/${sourceParams.repoType}/${sourceParams.repoId}/files/${sourceParams.artifactName}?signUrl=true&userId=${sourceParams.user}&version=${sourceParams.versionName}`
        let config = {
            method: 'get',
            url: `${packagesApi}`,
            headers: {
                Authorization: `${sourceParams.token}`
            },
            responseType: 'arraybuffer' as const // 指定响应类型为 'arraybuffer'，确保二进制数据以正确的格式接收
        }
        await axios(config).then(res => {
            fs.writeFileSync(fileDownloadPath, res.data)
            step.info(`Download artifact ${fileDownloadPath} successfully.`)

        }).catch(err => {
            step.info(`${err.message}`)
            if (err.response && err.response.data) {
                step.info(`${err.response.data}`)
            }
            throw new Error('Download artifact failed!')
        })
    }
    
    async writePackagesInfo(sourceParams: IGitSourceParams) {
        //write packages info
        step.info(`Write packages info`)
        step.addOutput(`outputsToEnv.CI_SOURCE_NAME=${sourceParams.artifactName}`)
        step.addOutput(`outputsToEnv.CI_SOURCE_NAME_${sourceParams.order}=${sourceParams.artifactName}`)
        step.addOutput(`outputsToEnv.CI_SOURCE_URL=${sourceParams.packagesDownloadUrl}`)
        step.addOutput(`outputsToEnv.CI_SOURCE_URL_${sourceParams.order}=${sourceParams.packagesDownloadUrl}`)
        step.addOutput(`outputsToEnv.CI_VERSION_NAME=${sourceParams.versionName}`)
        step.addOutput(`outputsToEnv.CI_VERSION_NAME_${sourceParams.order}=${sourceParams.versionName}`)
        step.exportEnvVar('CI_SOURCE_NAME', sourceParams.artifactName)
        step.exportEnvVar(`CI_SOURCE_NAME_${sourceParams.order}`, sourceParams.artifactName)
        step.exportEnvVar('CI_SOURCE_URL', sourceParams.packagesDownloadUrl)
        step.exportEnvVar(`CI_SOURCE_URL_${sourceParams.order}`, sourceParams.packagesDownloadUrl)
        step.exportEnvVar('CI_VERSION_NAME', sourceParams.versionName)
        step.exportEnvVar(`CI_VERSION_NAME_${sourceParams.order}`, sourceParams.versionName)
    }
}
